import { reactive, ref } from 'vue'
import { getOrderListApi } from '@/api'
import { queryOneAddressAPI } from '@/api/address'
import {getOrderDetailAPI, submitCommentAPI, updateOrderAPI,getCommentDetailAPI} from '@/api/order'
import { useOrderItemData } from '@/global/components/orderItem/hooks/useOrderItemData'
import { useCreateOrderData } from "@/pages/createOrder/hooks/useCreateOrderData";
export function useOrderData(userInfo) {
    const loading = ref(false);
    const popDialogRef = ref(null)
    const order = ref(null)
    const { handleOrderAction } = useOrderItemData()
    const orderParams = reactive({
        state: null,
        pageNum: 1,
        pageSize: 10,
        receiveUserId: null
    })
    let commentData = reactive({
        content: '',
        orderId: null,
        score: 0,
        userId: userInfo?.id,
        userName:userInfo?.name
    })
    const orderList = ref([])
    const addressData = reactive({
        takeAddress: null,
        receiveAddress: null
    })
    function getOrderData() {
        loading.value = true
        getOrderListApi(orderParams).then(res => {
            orderList.value = res
        }).finally(_ => {
            loading.value = false
        })
    }
    function getOrderDetail(id) {
        loading.value = true
        getOrderDetailAPI(id).then(res => {
            order.value = res
            commentData.orderId = res.id
            if(res.state === 4) {
                getCommentDetailAPI(res.id).then(result => {
                    for (let key in result) {
                        commentData[key] = result[key]
                    }
                })
            }
            getAddressData(res).finally(_ => {
                loading.value = false
            })
        })
    }
    function getAddressData(order) {
       return Promise.all([queryOneAddressAPI(order.takeAddressId), queryOneAddressAPI(order.receiveAddressId)])
           .then(result => {
               const [takeAddress,receiveAddress] = result
               addressData.takeAddress = takeAddress
               addressData.receiveAddress = receiveAddress
           })
    }
    function handleConfirm() {
        uni.showLoading()
        // 提交数据
        Promise.all([submitCommentAPI(commentData),updateOrderAPI({id: order.value?.id, state:4})])
            .then(res => {
                uni.showToast({title: '评价成功', icon: 'none'})
            }).finally(_ => {
                uni.hideLoading()
                popDialogRef.value?.close()
                getOrderDetail(commentData.orderId)
        })
    }
    function handleClickTab (item) {
        orderParams.state = item.id
        getOrderData()
    }
    return {
        orderParams,
        orderList,
        getOrderData,
        handleClickTab,
        loading,
        getOrderDetail,
        order,
        addressData,
        handleOrderAction,
        commentData,
        popDialogRef,
        handleConfirm
    }
}
